package com.jwthhealth_pub.wristband.view;

import android.bluetooth.BluetoothDevice;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomSheetBehavior;
import android.support.design.widget.BottomSheetDialog;
import android.view.KeyEvent;
import android.view.View;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jwthhealth_pub.R;
import com.jwthhealth_pub.common.base.BaseActivity;
import com.jwthhealth_pub.common.view.TitleLayout;
import com.jwthhealth_pub.old.sign.model.LoginModel;
import com.jwthhealth_pub.old.signutil.model.UserInfoModel;
import com.jwthhealth_pub.utils.Contas;
import com.jwthhealth_pub.wristband.presenter.IWristBandUserSettingPresenter;
import com.jwthhealth_pub.wristband.service.WristBandService;
import com.jwthhealth_pub.wristband.view.adapter.WristBandGuideDevListAdapter;
import com.weigan.loopview.LoopView;
import com.weigan.loopview.OnItemSelectedListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.jwthhealth_pub.common.LogUtil.makeLogTag;

/**
 * 手环 用户信息
 * Created by liuzhen on 2017/12/13.
 */

public class WristBandSettingUserInfoActivity extends BaseActivity implements IWristBandUserSettingPresenter.view {

    private final String TAG = makeLogTag(WristBandSettingUserInfoActivity.class);

    private static final int USERINFO_COMPLETE = 0;
    private static final int USERINFO_UNCOMPLETE = 1;

    View pageOne;
    @BindView(R.id.title_layout)
    TitleLayout titleLayout;
    @BindView(R.id.btn_height)
    RelativeLayout btnHeight;
    @BindView(R.id.btn_age)
    RelativeLayout btnAge;
    @BindView(R.id.btn_weight)
    RelativeLayout btnWeight;
    @BindView(R.id.tv_gender)
    TextView tvGender;
    @BindView(R.id.tv_age)
    TextView tvAge;
    @BindView(R.id.tv_hei)
    TextView tvHei;
    @BindView(R.id.tv_wei)
    TextView tvWei;
    @BindView(R.id.gr_gender)
    RadioGroup rgGender;
    @BindView(R.id.rb_famale)
    RadioButton rbFamale;
    @BindView(R.id.rb_male)
    RadioButton rbMale;
    private String mTargetValue;

    private String mGender = "-1";
    private String mHeight = "-1";
    private String mAge = "-1";
    private String mWeight = "-1";
    private String mStep = "-1";

    // TODO: 2017/12/14 targets
    private List<String> targetParameList;

    private String mTargetParam = "-1";
    private List<BluetoothDevice> mDevList;
    private WristBandGuideDevListAdapter mDevListAdapter;
    private WristBandService mWristBandService;
    private boolean isScaning;
    private boolean isConnect;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wristband_userinfo);
        ButterKnife.bind(this);

        pageOne = findViewById(R.id.layout_page_one);


        rgGender.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                if (i == R.id.rb_famale) {
                    mGender = "女";
                } else if (i == R.id.rb_male) {
                    mGender = "男";
                }
            }
        });

        loadSetting();
    }

    @Override
    protected void title() {
        titleLayout.setOnTitleLayoutListener(new TitleLayout.TitleLayoutListener() {
            @Override
            public void leftclick() {
//                back();
                finish();
            }

            @Override
            public void leftTextClick() {

            }

            @Override
            public void rightclick() {

            }

            @Override
            public void rightTextClick() {

            }
        });
    }

    private void showTargetDialog(final int type) {
        targetParameList = new ArrayList<>();

        switch (type) {
            case 0:
                //hei
                for (int i = 0; i < 120; i++) {
                    targetParameList.add((100 + i) + "cm");
                }
                break;
            case 1:
                //wei
                for (int i = 0; i < 120; i++) {
                    targetParameList.add((30 + i) + "kg");
                }
                break;
            case 2:
                //age
                for (int i = 0; i < 90; i++) {
                    targetParameList.add((20 + i) + "");
                }
                break;
            default:
                break;

        }

        final BottomSheetDialog shopbottomSheetDialog = new BottomSheetDialog(this);
        View view = View.inflate(this, R.layout.item_guide_target_step, null);
        shopbottomSheetDialog.setContentView(view);
        TextView completeBtn = view.findViewById(R.id.tv_complete);
        ImageView closeBtn = view.findViewById(R.id.btn_close);

        LoopView loopView = view.findViewById(R.id.loopView);
        loopView.setNotLoop();
        loopView.setItems(targetParameList);
        loopView.setInitPosition(60);

        String origanlStep = targetParameList.get(60);
        if (origanlStep != null) {
            mTargetValue = origanlStep;
        }

        loopView.setListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(int index) {
                mTargetValue = targetParameList.get(index);
            }
        });

        completeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                UserInfoModel infoModel = Contas.getObject(WristBandSettingUserInfoActivity.this, UserInfoModel.class);
                if (infoModel == null) infoModel = new UserInfoModel();

                if (type == 0) {
                    infoModel.setHeight(mTargetValue);
                    mHeight = mTargetValue;
                    tvHei.setText(mTargetValue);
                } else if (type == 1) {
                    infoModel.setWeight(mTargetValue);
                    mWeight = mTargetValue;
                    tvWei.setText(mTargetValue);
                } else if (type == 2) {
                    infoModel.setAge(mTargetValue);
                    mAge = mTargetValue;
                    tvAge.setText(mTargetValue);
                }

                Contas.putObject(WristBandSettingUserInfoActivity.this, infoModel);
                shopbottomSheetDialog.dismiss();
            }
        });

        closeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                shopbottomSheetDialog.dismiss();
            }
        });

        shopbottomSheetDialog.show();
    }

    private void showAgeAlert() {
        final BottomSheetDialog dateBottomSheetDialog = new BottomSheetDialog(this);
        View view = View.inflate(this, R.layout.item_guide_target_age, null);
        dateBottomSheetDialog.setContentView(view);

        //处理显示不全的问题
        View parent = (View) view.getParent();
        BottomSheetBehavior behavior = BottomSheetBehavior.from(parent);
        behavior.setState(BottomSheetBehavior.STATE_EXPANDED);

        TextView completeBtn = view.findViewById(R.id.tv_complete);
        ImageView closeBtn = view.findViewById(R.id.btn_close);

        final DatePicker datePicker = view.findViewById(R.id.datepicker);
//        datePicker.setMinDate(System.currentTimeMillis() + 86400000L);
        datePicker.setMaxDate(System.currentTimeMillis());

        datePicker.init(1980, 0, 1, null);

        completeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String mChoiceDate = "" + datePicker.getYear() + (datePicker.getMonth() + 1) + (datePicker.getDayOfMonth() + 1);
//                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd", Locale.getDefault());
                int choiceYear = datePicker.getYear();
                mChoiceDate = "" + datePicker.getYear() + "-" + (datePicker.getMonth() + 1) + "-" + (datePicker.getDayOfMonth());
                tvAge.setText((2017 - choiceYear) + "岁");
                mAge = (2017 - choiceYear) + "";
//                try {
//                    Date choiceDate = simpleDateFormat.parse(mChoiceDate);
//                    long difference = choiceDate.getTime() - System.currentTimeMillis();
//                    mChoiceDate = "" + datePicker.getYear() + "-" + (datePicker.getMonth() + 1) + "-" + (datePicker.getDayOfMonth());
//                    choiceDateText.setText(mChoiceDate);
//                    if (difference > 0 || Math.abs(difference) < 86400000) {
//                        mChoiceDate = "" + datePicker.getYear() + "-" + (datePicker.getMonth() + 1) + "-" + (datePicker.getDayOfMonth());
//                        choiceDateText.setText(mChoiceDate);
//                    } else {
//                        LogUtil.toast(getResources().getString(R.string.subscribe_alert_date));
//                    }

//                } catch (ParseException e) {
//                    e.printStackTrace();
//                }


                dateBottomSheetDialog.dismiss();
            }
        });

        closeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dateBottomSheetDialog.dismiss();
            }
        });

        dateBottomSheetDialog.show();
    }

    private boolean saveUserInfo() {
        if (mHeight.equals("-1") || mWeight.equals("-1") || mAge.equals("-1") || mGender.equals("-1")) {
            return false;
        }

        UserInfoModel userInfo = Contas.getObject(WristBandSettingUserInfoActivity.this, UserInfoModel.class);

        if (userInfo == null) userInfo = new UserInfoModel();

        userInfo.setHeight(mHeight);
        userInfo.setWeight(mWeight);
        userInfo.setAge(mAge);
        userInfo.setSex(mGender);
        Contas.putObject(WristBandSettingUserInfoActivity.this, userInfo);
        return true;
    }

    private void back() {
        if (saveUserInfo()) {
            setResult(RESULT_OK);
            finish();
        } else {
            Toast.makeText(WristBandSettingUserInfoActivity.this, "还有未完成的信息", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            back();
//
//            return true;
//        }


        return super.onKeyDown(keyCode, event);
    }

    @OnClick({R.id.btn_age, R.id.btn_height, R.id.btn_weight})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_age:
//                showTargetDialog(2);
                showAgeAlert();
                break;
            case R.id.btn_height:
                showTargetDialog(0);
                break;
            case R.id.btn_weight:
                showTargetDialog(1);
                break;
        }
    }

    @Override
    public void loadSetting() {
        LoginModel.DataBean userData = Contas.getObject(WristBandSettingUserInfoActivity.this, LoginModel.DataBean.class);
        if (userData == null) return;

        String userHei = userData.getHeight();
        if (userHei != null)
            tvHei.setText(userHei);

        String userWei = userData.getWeight();
        if (userWei != null)
            tvWei.setText(userWei);

        String userAge = userData.getAge();
        tvAge.setText(userAge);

        String sex = userData.getSex();
        if (sex.length() == 0) {
            if (sex.equals("0")) {
                rbFamale.setChecked(false);
                rbMale.setChecked(true);
            } else {
                rbFamale.setChecked(true);
                rbMale.setChecked(false);
            }
        }


    }
}
